clc
clear all

load('/Volumes/DPR/Data/IMERG/ERE_huffman/threshold/threshold_2018.mat');

Inpath='/Volumes/DPR/Data/IMERG/2018/';
Indir=dir(fullfile(Inpath,'*.HDF5'));
Inlength=length(Indir);
Outpath='/Volumes/IMERG/IMERG/ExtremeEvents/ERE_huffman/Extreme_Inventory/extreme_inventory_2018_01.mat';

extreme_inventory_temp = struct;

p=0;

for i=1:1488  
    i
    
    filename = fullfile(Inpath,Indir(i).name);
    tempSplit = strsplit(filename,'.');
    dateTime = strsplit(tempSplit{5},'-');
    year = str2double(dateTime{1}(1:4));
    month = str2double(dateTime{1}(5:6));
    day = str2double(dateTime{1}(7:8));
    
    startHour = str2double(dateTime{2}(2:3));
    startMin = str2double(dateTime{2}(4:5));
    startSec = str2double(dateTime{2}(6:7));
    
    endHour = str2double(dateTime{3}(2:3));
    endMin = str2double(dateTime{3}(4:5));
    endSec = str2double(dateTime{3}(6:7));
    
    startTime = strcat(dateTime{1}(1:4),'-',dateTime{1}(5:6),'-',dateTime{1}(7:8),{' '},dateTime{2}(2:3),...
        ':',dateTime{2}(4:5),':',dateTime{2}(6:7));
    endTime = strcat(dateTime{1}(1:4),'-',dateTime{1}(5:6),'-',dateTime{1}(7:8),{' '},dateTime{3}(2:3),...
        ':',dateTime{3}(4:5),':',dateTime{3}(6:7));
    
    lat = h5read(filename, '/Grid/lat');
    lon = h5read(filename, '/Grid/lon');
    latCONO = lat(1150:1391);
    lonCONO = lon(500:1101);
    
    preCal = h5read(filename, '/Grid/precipitationCal');       
    
    preCal(preCal<=0.01)=0;

    preCalCONO = preCal(1150:1391,500:1101);
    
    preCalCONO(preCalCONO < ERE_threshold) = 0;
        
    for j=1:242
        for k=1:602
            if preCalCONO(j,k) > 0
                p=p+1;
                EI_lat = latCONO(j);
                EI_lon = lonCONO(k);
                
                extreme_inventory_temp(p).id = p;
                extreme_inventory_temp(p).lat = EI_lat;
                extreme_inventory_temp(p).lon = EI_lon;
                extreme_inventory_temp(p).precip = preCalCONO(j,k);
                extreme_inventory_temp(p).threshold = ERE_threshold(j,k);
                extreme_inventory_temp(p).startTime = startTime{1};
                extreme_inventory_temp(p).endTime = endTime{1};
                % adding filename
                extreme_inventory_temp(p).filename = filename;
            end
        end
    end
end

tempTable = struct2table(extreme_inventory_temp);
extreme_inventory = sortrows(tempTable, 'precip','descend');

save(Outpath,'extreme_inventory')